<template>
  <el-dialog :title="prop.title" v-model="prop.showDialog" width="450px" @close="cancel(formRef)">
    <el-form ref="formRef" :model="form" label-width="150px" label-position="right">
      <el-form-item label="原因类型:" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入退货原因"/>
      </el-form-item>
      <el-form-item label="排序:" prop="sort">
        <el-input v-model.number="form.sort"/>
      </el-form-item>
      <el-form-item label="是否启用:" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(formRef)">Cancel</el-button>
        <el-button type="primary" @click="confirm(formRef)">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { Order } from '@/request/api';
import { ElMessage, FormInstance } from 'element-plus';
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';

let router = useRouter()
let formRef = ref<FormInstance>()
let form = ref<Order.IReturnReson>({
  id:null,
  name:'',
  sort:0,
  status:0,
  createTime:''
})
// 对话框是否显示
let prop = defineProps<{
  showDialog:boolean,
  title:string,
  id:number
}>()
let emit = defineEmits<{
  (e:"update:showDialog",param:boolean):void,
}>()

// 编辑初始化组件时触发，查询单个退货原因
let create =  function(){
  if(prop.id>=0){
    // console.log("编辑初始化");
    let result = Order.OrderQueryReturnReasonAPI(prop.id)
    result.then((val)=>{
      form.value = val
    })
  }
}
watch(()=>prop.id,(n,o)=>{
  create()
},{
  immediate:true
})
let updateAPI = async function(){
  let result = await Order.OrderUpdateReturnResonAPI(form.value)
  if(result===1){
    ElMessage({
      message:"修改成功",
      type:"success",
      duration:1500,
      onClose:()=>{
        router.go(0)
      }
    })
  }
}
//取消,清空表单并且关闭对话
const cancel = function(formEl:FormInstance | undefined){
  if(formEl){
    formEl.resetFields()
  }
  
  // 只读属性，不能直接更改
  // prop.showDialog = false
  emit("update:showDialog",false)
} 
// 确定,添加，执行cancel重置表单
const confirm = async function(formEl:FormInstance){
  if(prop.id>=0){
    // 编辑确定
    updateAPI()
    cancel(formEl)
    return true
  }
  // 添加确定
  let result = await Order.OrderAddReturnResonAPI(form.value)
  if(result===1){
    cancel(formEl)
    ElMessage({
      message:"添加成功",
      type:"success",
      duration:1500,
      onClose:()=>{
        router.go(0)
      }
    })
  }
}


</script>
<style scoped>
.el-input{
  width:200px
}
</style>